package com.ruoyi.web.controller.erpbase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.enums.SaleOrPurchType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.flowable.service.IFlowDefinitionService;
import com.ruoyi.flowable.service.IFlowTaskService;
import com.ruoyi.system.domain.ApprovalConfig;
import com.ruoyi.system.domain.FlowProcDefDto;
import com.ruoyi.system.domain.Funds;
import com.ruoyi.system.service.IFundsService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Collections;
import com.ruoyi.system.service.IApprovalConfigService;
import com.ruoyi.system.service.ICollectionsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 收退款Controller
 * 
 * @author he
 * @date 2025-10-20
 */
@RestController
@RequestMapping("/system/collections")
public class CollectionsController extends BaseController
{
    @Autowired
    private ICollectionsService collectionsService;

    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private IApprovalConfigService approvalConfigService;

    @Autowired
    private IFundsService fundsService;

    /**
     * 查询收退款列表
     */
    @PreAuthorize("@ss.hasPermi('system:collections:list')")
    @GetMapping("/list")
    public TableDataInfo list(Collections collections)
    {
        startPage();
        List<Collections> list = collectionsService.selectCollectionsList(collections);
        return getDataTable(list);
    }

    /**
     * 导出收退款列表
     */
    @PreAuthorize("@ss.hasPermi('system:collections:export')")
    @Log(title = "收退款", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Collections collections)
    {
        List<Collections> list = collectionsService.selectCollectionsList(collections);
        ExcelUtil<Collections> util = new ExcelUtil<Collections>(Collections.class);
        util.exportExcel(response, list, "收退款数据");
    }

    /**
     * 获取收退款详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:collections:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(collectionsService.selectCollectionsById(id));
    }

    /**
     * 新增收退款
     */
    @PreAuthorize("@ss.hasPermi('system:collections:add')")
    @Log(title = "收退款", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Collections collections)
    {
        //判断账户是否存在
        Funds funds = fundsService.selectFundsById(collections.getAccountId());
        if (ObjectUtils.isEmpty(funds)){
            return error("账户不存在");
        }

        return toAjax(collectionsService.insertCollections(collections));
    }

    /**
     * 修改收退款
     */
    @PreAuthorize("@ss.hasPermi('system:collections:edit')")
    @Log(title = "收退款", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Collections collections)
    {
        return toAjax(collectionsService.updateCollections(collections));
    }

    /**
     * 删除收退款
     */
    @PreAuthorize("@ss.hasPermi('system:collections:remove')")
    @Log(title = "收退款", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(collectionsService.deleteCollectionsByIds(ids));
    }

    /**
     * 批量发起收退款管理审批
     */
    @Log(title = "收退款管理", businessType = BusinessType.UPDATE)
    @PostMapping("/approvalStart")
    public AjaxResult approvalStart(@RequestBody List<Long> ids)
    {
        if (!approvalConfigService.isModuleEnabled("collections")) {
            return error("收退款管理模块未启用审批流，请先在审批配置中启用");
        }

        ApprovalConfig config = approvalConfigService.selectByModuleCode("collections");
        String flowName = config != null && StringUtils.isNotEmpty(config.getFlowName()) 
                ? config.getFlowName() : "收退款管理审核";

        List<Collections> allCollections = collectionsService.selectCollectionsList(new Collections());
        
        List<Collections> collectionsToApprove = new ArrayList<>();
        for (Collections collection : allCollections) {
            if (ids.contains(collection.getId())) {
                collectionsToApprove.add(collection);
            }
        }

        if (CollectionUtils.isNotEmpty(collectionsToApprove)) {
            Page<FlowProcDefDto> page = flowDefinitionService.list(flowName, 1, 10);
            List<FlowProcDefDto> records = page.getRecords();
            
            if (CollectionUtils.isEmpty(records)) {
                return error("未找到'" + flowName + "'流程定义，请先配置审批流程");
            }
            
            FlowProcDefDto flowProcDefDto = records.get(0);
            String deploymentId = flowProcDefDto.getDeploymentId();
            String flowId = flowProcDefDto.getId();
            AjaxResult ajaxResult1 = flowTaskService.flowFormData(deploymentId);

            Map<String, Object> variables = new HashMap<>();
            Object o = ajaxResult1.get("data");
            variables.put("formJson", o);

            List<Long> idsToUpdate = new ArrayList<>();
            for (Collections collection : collectionsToApprove) {
                variables.put("id", collection.getId());
                variables.put("account", collection.getAccount());
                variables.put("settlementNumber", collection.getSettlementNumber());
                variables.put("amount", collection.getAmount());
                
                AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById(flowId, variables);
                if (ajaxResult.isSuccess()) {
                    idsToUpdate.add(collection.getId());
                }
            }

            if (CollectionUtils.isNotEmpty(idsToUpdate)) {
                collectionsService.updateApprovalState(idsToUpdate, SaleOrPurchType.APPROVAL_YN.getCode());
            }
        }

        return toAjax(1);
    }

    /**
     * 审批流结束触发审核完成
     */
    @Log(title = "收退款管理", businessType = BusinessType.UPDATE)
    @PostMapping("/approvalEnd")
    public AjaxResult approvalEnd(@RequestBody Long id)
    {
        collectionsService.updateApprovalState(Arrays.asList(id), SaleOrPurchType.APPROVAL_YES.getCode());
        return toAjax(1);
    }
}
